package com.rrd.itext.html;

import java.util.ArrayList;
import java.util.List;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Element;
import com.itextpdf.tool.xml.NoCustomContextException;
import com.itextpdf.tool.xml.Tag;
import com.itextpdf.tool.xml.WorkerContext;
import com.itextpdf.tool.xml.css.CSS;
import com.itextpdf.tool.xml.exceptions.RuntimeWorkerException;
import com.itextpdf.tool.xml.html.HTMLUtils;
import com.itextpdf.tool.xml.html.ParaGraph;
import com.itextpdf.tool.xml.html.pdfelement.TabbedChunk;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;

public class ITextServiceParaGraph extends ParaGraph{
	@Override
	public List<Element> content(WorkerContext ctx, Tag tag, String content)
	{
		if (null != tag.getCSS().get(ITextServiceCSS.Property.FONT_VARIANT)
				&& ITextServiceCSS.Value.SMALL_CAPS.equalsIgnoreCase(tag.getCSS().get(ITextServiceCSS.Property.FONT_VARIANT))){
		    String sanitized = HTMLUtils.sanitize(content);

            List<Element> l = new ArrayList<Element>(1);
            char[] letters = sanitized.toCharArray();
            for(int i = 0; i < letters.length; i++){
                String letter = String.valueOf(letters[i]);
                boolean isUpcase = this.isUpcase(letter);
                if(!isUpcase){
                    letter = letter.toUpperCase();
                }
                if (sanitized.length() > 0) {
                    HtmlPipelineContext myctx;
                    try {
                        myctx = getHtmlPipelineContext(ctx);
                    } catch (NoCustomContextException e) {
                        throw new RuntimeWorkerException(e);
                    }
                    Chunk chunk = new Chunk(letter);
                    l.add(getCssAppliers().apply(chunk, tag, myctx));
                    if(!isUpcase){
                        adjustFontSize(chunk);
                    }
                }
            }
	        return l;
		}
		return super.content(ctx, tag, content);
	}
	
	private void adjustFontSize(Chunk chunk){
        float fontSize = chunk.getFont().getSize();
        if(fontSize < 0){
            fontSize = 12;
        }
        fontSize = fontSize - fontSize*0.2f;
        chunk.getFont().setSize(fontSize);
	}
	
	private boolean isUpcase(String letter){
	    if(letter.length() > 1){
	        return false;
	    }
	    if(letter.matches("[A-Z]")){
	        return true;
	    }else{
	        return false;
	    }
	}
}
